<?php
/**
 * Created by PhpStorm.
 * User: 王永清
 * Date: 2021/8/19
 * Time: 17:37
 */


class Article extends Base_Controller
{
    //es对象
    private $es;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('article_model');
        $this->load->model('cate_model');
        $this->load->model('rotation_model');
        $this->load->helper('common_helper');
        //加载CI表单验证库
        $this->load->library('form_validation');
        //实例化es类
        $this->es = getEs();
    }

    /*
     * 获取全部数据 get
     */
    public function index()
    {
        $data['article'] = $this->article_model->findAll();
        foreach ($data['article'] as &$v) {
            $v['img_url'] = 'http://cakephp.com/' . $v['image'];
            if (strlen($v['title']) >= 70) {
                $v['title'] = mb_substr($v['title'], 0, 70, 'utf-8') . '...';
            }
            $v['content'] = replace_specialChar($v['content']);
            if (strlen($v['content']) >= 40) {
                $v['content'] = mb_substr($v['content'], 0, 40, 'utf-8') . '...';
            }
        }

        $data['cate'] = $this->cate_model->findAll();
        $data['rotation'] = $this->rotation_model->findAll();
        $data['nav'] = $this->article_model->findNav();
        if ($data) {
            success($data, '获取成功！');
        } else {
            fail(500, '获取成功！');
        }
    }

    /*
     * 文章浏览
     */
    public function view($id)
    {
        //获取该文章的数据和该文章的用户数据
        $data = $this->article_model->findOne($id);
        //获取该用户专栏的数据
        $column = $this->article_model->findColumn($data['user_id']);
        //获取该用户浏览量前五的文章
        $article = $this->article_model->findFiveArticle($data['user_id']);
        //获取该用户的最新文章
        $new = $this->article_model->findNewArticle($data['user_id']);
        $data['update_time'] = date("Y-m-d H:i:s", $data['update_time']);
        $data['image'] = "http://cakephp.com/" . $data['image'];
        $data['column'] = $column;
        $data['article'] = $article;
        $data['new'] = $new;
        //文章浏览量的实现
        //获取当前访问者的ip
        $ip = $_SERVER["REMOTE_ADDR"];
        $key = $ip . '_pageView_' . $id;
        $rankKey = 'articleViewRank';
        $lockKey = $id . '_articleViewLock_' . $ip;
        $conn = getRedis();
        $conn->selectDb(0);
        //8640秒时间内多次访问无效
        if ($conn->setNxExpire($lockKey, 1, 3)) {
            //增加阅读量
            $conn->incr($key);
            //放到排行榜中
            $conn->zIncrBy($rankKey, 1, $id);
        }
        success($data);
    }

    /*
     * 对文章发表评论
     */
    public function comment()
    {
        $data = $this->input->post();
        if (!$data['user_id'] || !$data['user_id_2'] || !$data['article_id'] || !$data['content']) {
            fail('400', '参数错误!');
        }
        $data1 = [
            'user_id' => $data['user_id'],
            'user_id_2' => $data['user_id_2'],
            'article_id' => $data['article_id'],
            'content' => $data['content'],
            'create_time' => time(),
            'update_time' => time()
        ];
        $status = $this->article_model->addComment($data1);
        if (!$status) {
            fail(400, '评论失败!');
        }
        success($status, '发表评论成功!');
    }

    /*
     * 文章点赞/取消点赞
     */
    public function fabulous()
    {
        $data = $this->input->post();
        if (empty($data['user_id'])) {
            fail('400', '点赞异常!');
        }
        if (empty($data['article_id'])) {
            fail('400', '点赞异常!');
        }
        //set类型存储全部点赞的文章
        $conn = getRedis();
        $conn->selectDb(0);
        $key1 = "like_article";
        //该文章是否已经在set中
        if (!$conn->sisMember($key1, $data['article_id'])) {
            $conn->sAdd($key1, $data['article_id']);
        }
        //set类型存储点赞文章的用户id
        $key2 = "user_like" . $data['article_id'];
        //该文章是否已经被该用户点赞
        $status = $conn->sisMember($key2, $data['user_id']);
        //hash类型存储点赞的详细信息
        $key3 = $data['user_id'] . "_like_" . $data['article_id'];
        if (!$status) {
            $conn->sAdd($key2, $data['user_id']);
            $res = [
                'user_id' => $data['user_id'],
                'article_id' => $data['article_id'],
                'create_time' => time()
            ];
            $conn->hMSet($key3, $res);
        }
        //存储文章点赞总数
        $key4 = "article_" . $data['article_id'] . "_count";
        //若该用户未给该文章点赞
        if (!$status) {
            $conn->incr($key4);
        } else {
            //已经点赞了删除hash集合
            $conn->del($key3);
            $conn->del($key2);
            $conn->decr($key4);
        }
        //点赞总数
        $res = $conn->get($key4);
        success($res, '点赞成功！');
    }

    /*
     * 发布文章
     */
    public function publish()
    {
        $data = $this->input->post();
        $rules = [
            [
                'field' => 'user_id',
                'label' => '发布文章用户id',
                'rules' => 'required'
            ],
            [
                'field' => 'content',
                'label' => '内容',
                'rules' => 'required'
            ],
            [
                'field' => 'title',
                'label' => '标题',
                'rules' => 'required'
            ],
            [
                'field' => 'cate_id',
                'label' => '分类id',
                'rules' => 'required'
            ],
            [
                'field' => 'cate_id',
                'label' => '标签id',
                'rules' => 'required'
            ],
            [
                'field' => 'column_id',
                'label' => '专栏id',
                'rules' => 'required'
            ]
        ];
        $this->form_validation->set_data($data);
        $this->form_validation->set_rules($rules);
        if ($this->form_validation->run() == FALSE) {
            $data = $this->form_validation->error_array();
            $data = current($data);
            fail('400', $data);
        }
        $data1 = [
            'user_id' => $data['user_id'],
            'cate_id' => $data['cate_id'],
            'column_id' => $data['column_id'],
            'tag_id' => $data['tag_id'],
            'title' => $data['title'],
            'content' => $data['content'],
            'create_time' => time(),
            'update_time' => time(),
        ];
        $res = $this->article_model->publish($data1);
        if (!$res) {
            fail(400, '发布文章失败!');
        }
        if (!empty($data['id'])) {
            //修改操作
            $this->es->updateDoc('articles', $data['id'], $data1);
            success($res, '修改文章成功!');
        } else {
            //新增操作
            //新增成功向es中新增数据
            $this->es->SaveDoc('articles', $data['id'], $data1);
            success($res, '发布文章成功!');
        }


    }

    /*
     * 删除文章
     */
    public function delArticle()
    {
        $res = $this->input->post();
        if (!$res['id']) {
            fail('400', '删除错误!');
        }
        $res = $this->article_model->delArticle($res['id']);
        if (!$res) {
            fail('400', '删除错误!');
        }
        //删除es中保存的数据
        $this->es->deleteDoc('articles', $res['id']);
        success($res, '删除成功!');
    }

    /*
     * 修改文章页面展示
     */
    public function alertArticle()
    {
        $post = $this->input->post();
        if (empty($post['id'])) {
            fail(400, '参数错误!');
        }
        $res = $this->article_model->findOne($post['id']);
        if (!$res) {
            fail(400, '文章查询失败!');
        }
        success($res);
    }

    /*
     * 新增专栏
     */
    public function addColumn()
    {
        $data = $this->input->post();
        $rules = [
            [
                'field' => 'user_id',
                'label' => '用户id',
                'rules' => 'required',
                'errors' => [
                    'required' => '用户id不能为空!'
                ]
            ],
            [
                'field' => 'name',
                'label' => '专栏名称',
                'rules' => 'required',
                'errors' => [
                    'required' => '学校名称不能为空!'
                ]
            ],
        ];
        $res = $this->validate($data, $rules);
        if ($res !== true) {
            fail(400, $res);
        }
        $data['create_time'] = time();
        $data['update_time'] = time();
        $res = $this->article_model->addColumn($data);
        if ($res) {
            success([], '操作成功!');
        }
        fail(400, '操作失败');
    }

    /*
     * 查询检索操作
     */
    public function search()
    {
        $data = $this->input->post();
        if (!empty($data['keyword'])) {
            $body = [
                'query' => [
                    'bool' => [
                        'should' => [
                            ['match' => ['title' => $data['keyword']]],
                            ['match' => ['desc' => $data['keyword']]],
                            ['match' => ['content' => $data['keyword']]],
                            ['match' => ['nickname' => $data['keyword']]],
                        ]
                    ]
                ]
            ];
            $res = $this->es->searchDoc('articles', $body);
            success($res);
        }
    }
}